#!/bin/bash
#环境变量

JAVA_HOME=/data/cmttg/soft/jdk1.8.0_231

export JRE_HOME=/data/cmttg/soft/jdk1.8.0_231/jre

export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH

export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

#基本参数

APP_NAME=data-api-0.0.1-SNAPSHOT.jar
APP_XMS=1024m
APP_XMX=4096m
APP_MetaspaceSize=1024m
APP_MaxMetaspaceSize=2048m
APP_noupt_dir=./api.out
date=$(date +%Y-%m-%d)
v_num=$RANDOM

usage() {
  echo "case:sh run.sh [start | stop | restart | status]"
  echo "please input  ./*.sh start or ./*sh restart"
  exit 1
}

# 判断当前服务是否已经启动的函数

is_exist() {
  pid=$(ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}')
  if [ -z "${pid}" ]; then
    echo "pid is null."
    return 1
  else
    echo "${APP_NAME} running. pid=${pid}"
    return 0
  fi

}

#备份文件

bak() {
  # 创建文件夹
  index=back/$(date +%Y-%m-%d)/$(date +%H-%M)
  echo "删除过期的文件夹 5天以前。"
  tt=$(date +%Y-%m-%d -d -5day)
  today=$(date -d $tt +%s)
  mdir=/home/data/jenkins/${package-name}-${profileActive}/back
  for file in $(ls back/); do
    if [ -d $mdir/$file ]; then
      if [ $(date -d "$file" +%s) -lt $today ]; then
        echo " 小于  $file < $tt  删除"
        ./del.sh $mdir/$file
      fi
    fi
  done

  sudo mkdir -p $index
  echo "创建文件夹 $index"

  echo "备份文件到今日文件夹 $index"
  #sudo mv data-1.0.0-prod data-1.0.0-prod.zip  log.sh  publish.sh $index

  ls back
  echo "备份完毕"
}

#启动服务命令

start() {
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} running. pid=${pid}"
  else
    if [ ! -d "./logs" ]; then
      mkdir logs
    fi
    nohup java -d64 -server -verbose:gc -Xloggc:./logs/gc_$(date +%Y%m%d%H%M%S).log -XX:+DisableExplicitGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -XX:+PrintGCTimeStamps -XX:+PrintClassHistogram -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./logs -XX:ErrorFile=./logs/hs_err_%p.log -XX:+UseG1GC -Xms${APP_XMS} -Xmx${APP_XMX} -XX:MaxMetaspaceSize=${APP_MaxMetaspaceSize} -XX:MetaspaceSize=${APP_MetaspaceSize} -jar ${APP_NAME} >${APP_noupt_dir} 2>&1 &
    is_exist
  fi
}

#停止服务命令

stop() {
  echo "执行stop方法"
  is_exist
  if [ $? -eq 0 ]; then
    kill -9 $pid
    echo "${pid} stop"
  else
    echo "${APP_NAME} not running"
  fi

}

#重启命令

restart() {
  stop
  start
}

case "$1" in
"bak")
  bak
  ;;

"status")
  is_exist
  ;;

"start")
  start
  ;;

"stop")
  stop
  ;;

"restart")
  restart
  ;;

*)
  usage
  ;;
esac
